package com.dgut.forum.services.impl;

import com.dgut.forum.common.AppResult;
import com.dgut.forum.common.ResultCode;
import com.dgut.forum.dao.ArticleMapper;
import com.dgut.forum.dao.ArticleReplyMapper;
import com.dgut.forum.exception.ApplicationException;
import com.dgut.forum.model.Article;
import com.dgut.forum.model.ArticleReply;
import com.dgut.forum.services.IArticleReplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private ArticleServiceImpl articleService;
    @Override
    public void create(ArticleReply reply) {
        //校验参数
        if(reply==null&&reply.getArticleId()==null&&reply.getPostUserId()==null&&reply.getContent()==null){
            log.info("提交回复是参数校验异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验帖子状态
        //获取到
        Article article=articleService.selectById(reply.getArticleId());
        if(article==null||article.getDeleteState()==1){
            log.info("要留言的帖子不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            log.info("要回复的帖子状态异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED_STATE));
        }
        //往评论表中插入回复
        ArticleReply articleReply=new ArticleReply();
        articleReply.setArticleId(reply.getArticleId());
        articleReply.setPostUserId(reply.getPostUserId());
        articleReply.setContent(reply.getContent());
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);

        int row=articleReplyMapper.insertSelective(articleReply);
        if(row!=1){
            log.info("新增回复错误,服务器出错");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子回复数
        articleService.addOneToArticleReplyCount(reply.getArticleId());
        log.info("新增回复成功");
    }

    /*
     * 获得帖子的所有评论
     * */
    @Override
    public List<ArticleReply> selectAllReplies(Long articleId) {
        if(articleId==null||articleId<=0){
            log.warn("获取帖子评论,帖子Id不合法,id="+articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleReplyMapper.selectAllReplies(articleId);
    }
}
